<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getProDetail, getProComments } from '@/apis/product'
import { addCart } from '@/apis/cart'
import defaultImg from '@/assets/default-avatar.png'
import CountBox from '@/components/CountBox.vue'
const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const details = ref({})
const images = ref([])
const commentList = ref([])
const cartTotal = ref(0)
const showPannel = ref(false)
const addCount = ref(1)
const mode = ref('cart')
// 获取地址栏的id /prodetail/:id  参数params获取
const goodsId = computed(() => route.params.id)
// 获取详情页信息
const getDetail = async() => {
  const { data: { detail } } = await getProDetail(goodsId.value)
  details.value = detail
  images.value = detail.goods_images
}
// 获取详情页评论
const totalComments = ref(0)
const getComments = async() => {
   const { data: { list, total } } = await getProComments(goodsId.value, 3)
   commentList.value = list
   totalComments.value = total
}
onMounted(() => {
  getDetail() 
  getComments()
})
const current = ref(0)
const onChange = (index) => {
   current.value = index
}

const addFn = () => {
  mode.value = 'cart'
  showPannel.value = true
}
const buyNow = () => {
  mode.value = 'buyNow'
  showPannel.value = true
}

const loginConfirm = () => {
  if (!userStore.userInfo?.token) {
   // eslint-disable-next-line no-undef
   showConfirmDialog({
     title: '温馨提示',
     message:
       '此时需要先登录才能继续操作哦',
     confirmButtonText: '去登录',
     confirmButtonColor: '#ee0a24',
     cancelButtonText: '再逛逛'
   })
   .then(() => {
     // on confirm
     router.replace({
       path: '/login',
       query: {
         backUrl: route.fullPath
       }
     })
   })
   .catch(() => {})
   return true
   }
   return false
}

const pushCart = async() => {
  if (loginConfirm()) {
    return
  }
  const { data } = await addCart(goodsId.value, addCount.value, details.value.skuList[0].goods_sku_id)
  cartTotal.value = data.cartTotal
  // eslint-disable-next-line no-undef
  showToast('加入购物车成功')
  showPannel.value = false
}
const goBuyNow = () => {
  if (loginConfirm()) {
    return
  }
  router.push({
    path: '/pay',
    query: {
      mode: 'buyNow',
      goodsId: goodsId.value,
      goods_sku_id: details.value.skuList[0].goods_sku_id,
      goodsNum: addCount.value
    }
  })
}
defineOptions({
  name: 'ProDetailIndex'
})
</script>

<template>
  <div class="prodetail">
    <!-- 顶部导航 -->
    <van-nav-bar fixed title="商品详情页" left-arrow @click-left="$router.go(-1)" />

    <!-- 轮播图 -->
    <van-swipe :autoplay="4000" @change="onChange">
      <van-swipe-item v-for="(image, index) in images" :key="index">
        <img :src="image.external_url" />
      </van-swipe-item>
      <template #indicator>
        <div class="custom-indicator">{{ current + 1 }} / {{ images.length }}</div>
      </template>
    </van-swipe>

    <!-- 商品说明 -->
    <div class="info">
      <div class="title">
        <div class="price">
           <span class="now">￥{{ details.goods_price_min }}</span>
           <span class="oldprice">￥{{ details.goods_price_max }}</span>
        </div>
        <div class="sellcount">
            已售 {{ details.goods_sales }} 件
        </div>
      </div>

      <div class="msg text-ellipsis-2">
         {{ details.goods_name }}
      </div>

      <div class="service">
        <div class="left-words">
          <span><van-icon name="passed" />七天无理由退货</span>
          <span><van-icon name="passed" />48小时发货</span>
        </div>
        <div class="right-icon">
          <van-icon name="arrow" />
        </div>
      </div>
    </div>

    <!-- 商品评价 -->
    <div class="comment">
      <div class="comment-title">
        <div class="left">商品评价 ({{ totalComments }}条)</div>
        <div class="right">查看更多 <van-icon name="arrow" /> </div>
      </div>
      <div class="comment-list">
        <div class="comment-item" v-for="item in commentList" :key="item.comment_id">
          <div class="top">
            <img :src="item.user.avatar_url || defaultImg" alt="">
            <div class="name">{{ item.user.nick_name }}</div>
            <van-rate :size="16" :model-value="item.score / 2" color="#ffd21e" void-icon="star" void-color="#eee"/>
          </div>
          <div class="content">
             {{ item.content }}
          </div>
          <div class="time">
             {{ item.create_time }}
          </div>
        </div>
      </div>
    </div>

    <!-- 商品描述 -->
    <div class="desc" v-html="details.content"></div>

    <!-- 底部 -->
    <div class="footer">
      <div class="icon-home" @click="router.push('/')">
         <van-icon name="wap-home-o" />
         <span>首页</span>
      </div>
      <div class="icon-cart" @click="router.push('/cart')">
        <span v-if="cartTotal > 0" class="num">{{ cartTotal }}</span>
        <van-icon name="shopping-cart-o" />
        <span>购物车</span>
      </div>
      <div class="btn-add" @click="addFn">
        加入购物车
      </div>
      <div class="btn-buy" @click="buyNow">
        立即购买
      </div>
    </div>

    <!-- 弹层 -->
    <van-action-sheet v-model:show="showPannel" :title="mode === 'cart' ? '加入购物车' : '立刻购买'">
      <div class="product">
        <div class="product-title">
          <div class="left">
            <img :src="details.goods_image" alt="">
          </div>
          <div class="right">
            <div class="price">
              <span>¥</span>
              <span class="nowprice">{{ details.goods_price_min }}</span>
            </div>
            <div class="count">
              <span>库存</span>
              <span>{{ details.stock_total }}</span>
            </div>
          </div>
        </div>
        <div class="num-box">
          <span>数量</span>
          <!-- v-model 本质上 :value 和 @input 的简写 -->
          <CountBox v-model="addCount"></CountBox>
        </div>

        <!-- 有库存才显示提交按钮 -->
        <div class="showbtn" v-if="details.stock_total > 0">
          <div class="btn" v-if="mode === 'cart'" @click="pushCart">加入购物车</div>
          <div class="btn now" v-else @click="goBuyNow">立刻购买</div>
        </div>

        <div class="btn-none" v-else>该商品已抢完</div>
      </div>
    </van-action-sheet>
  </div>
</template>

<style lang="less" scoped>
.prodetail {
  padding-top: 46px;
  :deep(.van-nav-bar__title) {
      font-weight: normal;
  }
  :deep(.van-icon-arrow-left) {
    color: #333;
  }
  img {
    display: block;
    width: 100%;
  }
  .custom-indicator {
    position: absolute;
    right: 10px;
    bottom: 10px;
    padding: 5px 10px;
    font-size: 12px;
    background: rgba(0, 0, 0, 0.1);
    border-radius: 15px;
  }
  .desc {
    width: 100%;
    overflow: scroll;
    :deep(img) {
      display: block;
      width: 100%!important;
    }
  }
  .info {
    padding: 10px;
  }
  .title {
    display: flex;
    justify-content: space-between;
    .now {
      color: #fa2209;
      font-size: 20px;
    }
    .oldprice {
      color: #959595;
      font-size: 16px;
      text-decoration: line-through;
      margin-left: 5px;
    }
    .sellcount {
      color: #959595;
      font-size: 16px;
      position: relative;
      top: 4px;
    }
  }
  .msg {
    font-size: 16px;
    line-height: 24px;
    margin-top: 5px;
  }
  .service {
    display: flex;
    justify-content: space-between;
    line-height: 40px;
    margin-top: 10px;
    font-size: 16px;
    background-color: #fafafa;
    .left-words {
      span {
        margin-right: 10px;
      }
      .van-icon {
        margin-right: 4px;
        color: #fa2209;
      }
    }
  }

  .comment {
    padding: 10px;
  }
  .comment-title {
    display: flex;
    justify-content: space-between;
    .right {
      color: #959595;
    }
  }

  .comment-item {
    font-size: 16px;
    line-height: 30px;
    .top {
      height: 30px;
      display: flex;
      align-items: center;
      margin-top: 20px;
      img {
        width: 20px;
        height: 20px;
      }
      .name {
        margin: 0 10px;
      }
    }
    .time {
      color: #999;
    }
  }

  .footer {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 55px;
    background-color: #fff;
    border-top: 1px solid #ccc;
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    .icon-home, .icon-cart {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      .van-icon {
        font-size: 24px;
      }
    }
    .btn-add,
    .btn-buy {
      height: 36px;
      line-height: 36px;
      width: 120px;
      border-radius: 18px;
      background-color: #ffa900;
      text-align: center;
      color: #fff;
      font-size: 14px;
    }
    .btn-buy {
      background-color: #fe5630;
    }
  }
}

.tips {
  padding: 10px;
}

// 弹层的样式
.product {
  .product-title {
    display: flex;
    .left {
      img {
        width: 90px;
        height: 90px;
      }
      margin: 10px;
    }
    .right {
      flex: 1;
      padding: 10px;
      .price {
        font-size: 14px;
        color: #fe560a;
        .nowprice {
          font-size: 24px;
          margin: 0 5px;
        }
      }
    }
  }

  .num-box {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    align-items: center;
  }

  .btn, .btn-none {
    height: 40px;
    line-height: 40px;
    margin: 20px;
    border-radius: 20px;
    text-align: center;
    color: rgb(255, 255, 255);
    background-color: rgb(255, 148, 2);
  }
  .btn.now {
    background-color: #fe5630;
  }
  .btn-none {
    background-color: #cccccc;
  }
}

.footer .icon-cart {
  position: relative;
  padding: 0 6px;
  .num {
    z-index: 999;
    position: absolute;
    top: -2px;
    right: 0;
    min-width: 16px;
    padding: 0 4px;
    color: #fff;
    text-align: center;
    background-color: #ee0a24;
    border-radius: 50%;
  }
}
</style>